package com.youdianstar.app.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.youdianstar.app.R
import com.youdianstar.app.databinding.LayoutItemOrderBinding
import com.youdianstar.app.entity.OrderInfo
import com.youdianstar.app.entity.NewOrderInfo

import com.youdianstar.app.common.util.DateUtil
import com.youdianstar.app.common.util.MathUtil

import com.youdianstar.app.ui.OrderDetailActivity
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.support.paymentActionIntent
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.ex.parseTx
import com.youdianstar.app.common.auko.startActivity


/**
 * File: OrderPagingAdapter
 * Author: 82149 Create: 2021/11/11 19:19
 * Changes (from 2021/11/11)
 * --------------------------------------------------
 * description: 订单列表
 * ---------------------------------------------------
 *
 */
class OrderPagingAdapter : PagingDataAdapter<Any, RecyclerView.ViewHolder>(differCallback) {
    companion object {
        val TAG = "OrderPagingAdapter"
        val differCallback = object : DiffUtil.ItemCallback<Any>() {
            override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean {
                return when {
                    oldItem is OrderInfo && newItem is OrderInfo -> oldItem.orderNo == newItem.orderNo
                    oldItem is NewOrderInfo && newItem is NewOrderInfo -> oldItem.uuid == newItem.uuid
                    else -> oldItem == newItem
                }
            }

            override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean {
                return oldItem == newItem
            }
        }
    }

    internal class OrderVH(val binding: LayoutItemOrderBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bindData(order: Any) {
            when (order) {
                is OrderInfo -> {
                    // 处理OrderInfo类型
                    when (order.state) {
                        DataCode.STATE_RENTING -> {
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_renting)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        DataCode.STATE_COMPLETE, DataCode.STATE_CANCEL, DataCode.STATE_REFUND, DataCode.STATE_PURCHASE_PB -> {
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_complete)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        DataCode.STATE_UNPAID -> {
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_process)
                            binding.llBottomPay.visibility = View.VISIBLE
                        }
                        DataCode.STATE_PROCESS -> {
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_process)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        DataCode.STATE_REPORT_LOSS -> {
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_loss)
                            binding.llBottomPay.visibility = View.GONE
                        }
                    }

                    // Order state: 1-租借中 2-待支付 3-已完成 4-已取消 5-调查中 6-已退款 7-已报失
                    val stateStr = when (order.state) {
                        DataCode.STATE_RENTING -> binding.root.context.getString(R.string.order_renting)
                        DataCode.STATE_COMPLETE -> binding.root.context.getString(R.string.order_completed)
                        DataCode.STATE_UNPAID -> binding.root.context.getString(R.string.order_pendingPayment)
                        DataCode.STATE_PROCESS -> binding.root.context.getString(R.string.order_underInvestigation)
                        DataCode.STATE_REPORT_LOSS -> binding.root.context.getString(R.string.order_completed) //已报失 文本显示已完成 order_reportedLost
                        else -> "--"
                    }
                    binding.tvName.text = stateStr
                    // 列表 amount: 待支付 money; 已完成/已报失/买宝 realAmount ; 租借中/调查中 orderAmount
                    val symbolStr = DataAppManager.instance.symbolTx()
                    val amountTx = when (order.state) {
                        DataCode.STATE_UNPAID -> symbolStr+MathUtil.round(order.unpaidAmountValue())
                        DataCode.STATE_COMPLETE, DataCode.STATE_REPORT_LOSS, DataCode.STATE_PURCHASE_PB -> {
                            symbolStr+MathUtil.round(order.realAmountValue())
                        }
                        else -> symbolStr+MathUtil.round(order.orderAmountValue())
                    }
                    setText(binding.tvAmount, amountTx)

                    // 时间与地址
                    setText(binding.tvTime, DateUtil.getOrderTime(order.createTime))
                    setText(binding.tvDes, order.rentBranchName.parseTx())
                }
                is NewOrderInfo -> {
                    // 处理NewOrderInfo类型
                    when (order.usingStatus) {
                        1 -> { // 使用中
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_renting)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        2 -> { // 已归还
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_complete)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        3, 4, 5 -> { // 已购买(正常/丢失/超时)
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_complete)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        6 -> { // 其他状态
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_process)
                            binding.llBottomPay.visibility = View.GONE
                        }
                        else -> {
                            binding.ivStatus.setBackgroundResource(R.drawable.oval_order_process)
                            binding.llBottomPay.visibility = View.GONE
                        }
                    }

                    // 设置状态文本
                    val stateStr = when (order.usingStatus) {
                        1 -> binding.root.context.getString(R.string.order_renting)
                        2 -> binding.root.context.getString(R.string.order_completed)
                        3 -> binding.root.context.getString(R.string.order_completed) // 已购买(正常)
                        4 -> binding.root.context.getString(R.string.order_reportedLost) // 已购买(丢失)
                        5 -> binding.root.context.getString(R.string.order_completed) // 已购买(超时)
                        6 -> binding.root.context.getString(R.string.order_underInvestigation) // 其他状态
                        else -> "--"
                    }
                    binding.tvName.text = stateStr
                    
                    // Order amount - 根据状态显示不同金额
                    val symbolStr = DataAppManager.instance.symbolTx()
                    val amountTx = when (order.usingStatus) {
                        1 -> { // 使用中 - 显示当前费用
                            symbolStr + MathUtil.round(order.fee)
                        }
                        2 -> { // 已归还 - 显示支付费用
                            if (order.pay) {
                                symbolStr + MathUtil.round(order.payFee)
                            } else {
                                symbolStr + MathUtil.round(order.fee)
                            }
                        }
                        3, 4, 5 -> { // 已购买 - 显示支付费用
                            symbolStr + MathUtil.round(order.payFee)
                        }
                        else -> {
                            symbolStr + MathUtil.round(order.fee)
                        }
                    }
                    setText(binding.tvAmount, amountTx)

                    // 时间与地址
                    setText(binding.tvTime, DateUtil.getOrderTime(order.createTime))
                    setText(binding.tvDes, order.box1SiteName)
                }
                else -> {
                    // 未知类型，显示默认值
                    binding.tvName.text = "--"
                    binding.tvAmount.text = "--"
                    binding.tvTime.text = "--"
                    binding.tvDes.text = "--"
                }
            }
        }

        private fun setText(view: TextView, text: String) {
            view.text = text
        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        getItem(position)?.let {
            (holder as OrderVH).bindData(it)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val orderItem = OrderVH(LayoutItemOrderBinding.inflate(LayoutInflater.from(parent.context), parent, false))
        orderItem.itemView.setOnClickListener {
            val data = getItem(orderItem.layoutPosition)
            data?.let { itemData ->
                when (itemData) {
                    is OrderInfo -> {
                        parent.context.startActivity<OrderDetailActivity>(
                            Extra.IT_ORDERNO to itemData.orderNo,
                            Extra.IT_TYPE to 0
                        )
                    }
                    is NewOrderInfo -> {
                        parent.context.startActivity<OrderDetailActivity>(
                            Extra.IT_ORDERNO to itemData.uuidLastSix,
                            Extra.IT_TYPE to 0
                        )
                    }
                }
            }
        }

        orderItem.binding.llBottomPay.setOnClickListener {
            val itemData = getItem(orderItem.layoutPosition)
            itemData?.let { data ->
                when (data) {
                    is OrderInfo -> {
                        if (data.state == DataCode.STATE_UNPAID) {
                            // 待支付跳转支付
                            if (data.lost){
                                paymentActionIntent(parent.context, BisType.Bis_Loss, data.money, orderNo = data.orderNo, orderInfo = data)
                            }else{
                                paymentActionIntent(parent.context, BisType.Bis_Rent, data.money, orderNo = data.orderNo, orderInfo = data)
                            }
                        }
                    }
                    is NewOrderInfo -> {
                        if (data.usingStatus == 2 && !data.pay) {
                            // 已归还但未支付，跳转支付
                            // 注意：paymentActionIntent 期望 OrderInfo 类型，这里需要转换或使用其他方式
                            // 暂时注释掉，避免类型错误
                            // paymentActionIntent(parent.context, BisType.Bis_Rent, data.fee, orderNo = data.uuidLastSix, orderInfo = data)
                        }
                    }
                }
            }
        }
        return orderItem
    }
}